import { LoadingOutlined, WarningFilled } from '@ant-design/icons';
import { ModalForm } from '@ant-design/pro-components';
import { Button, message, Result } from 'antd';
import { useState } from 'react';

type OperReturn = {
  success: boolean;
  message: string;
};
interface ConfirmModal {
  reload: () => void;
  operFunc: () => Promise<OperReturn>;
  text?: string | React.ReactNode;
  danger?: boolean;
  type?: 'button' | 'link';
  btnText?: string;
  titleText?: string;
}

export default (props: ConfirmModal) => {
  const {
    titleText = '删除警告',
    text = '确认删除当前项？',
    operFunc,
    reload,
    danger,
    type = 'link',
    btnText = '删除',
  } = props;
  const [waiting, setWaiting] = useState<boolean>(danger || false);
  const [loading, setLoading] = useState(false);
  const btnClick = () => {
    if (danger) {
      setWaiting(true);
      setTimeout(() => {
        setWaiting(false);
      }, 2500);
    }
  };
  return (
    <ModalForm
      title={
        <>
          <WarningFilled
            style={{
              color: danger ? 'red' : '#efaf41',
              marginRight: '5px',
            }}
          />
          {titleText}
        </>
      }
      width="35vw"
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      trigger={
        type == 'link' ? (
          <a onClick={btnClick}>{btnText}</a>
        ) : (
          <Button onClick={btnClick}>{btnText}</Button>
        )
      }
      submitter={{
        submitButtonProps: {
          danger,
          loading: danger && waiting,
        },
      }}
      onFinish={async () => {
        setLoading(true);
        const res = await operFunc();
        setLoading(false);
        if (res.success) {
          reload();
          message.success({ content: res.message, key: 'oper_key' });
          return true;
        }
        message.error({ content: res.message, key: 'oper_key' });
        return false;
      }}
    >
      {!loading && (
        <Result
          icon={null}
          subTitle={
            <div
              style={{
                fontSize: '16px',
                color: 'black',
              }}
            >
              {text}
            </div>
          }
        />
      )}
      {loading && <Result title="正在操作，请稍后..." icon={<LoadingOutlined spin />} />}
    </ModalForm>
  );
};
